package org.al.poc.sockets;

import java.net.ServerSocket;
import java.net.Socket;

import org.al.poc.persistence.beans.Connection;
import org.al.poc.persistence.beans.Order;

public abstract class AbstractServerThread implements Runnable {

	
	protected ServerSocket serverSocket;
	protected Socket socket;
	
	
	
	public AbstractServerThread (ServerSocket ss) {
		this.serverSocket = ss;
	}

	protected abstract void processOrder(Order object) throws Exception;
	protected abstract void processConnection(Connection object) throws Exception;
	
	
	
	@Override
	public void run() {
		
		boolean shouldStop = false;
		
		while (! shouldStop) {

			socket = null;

			try {
				socket = serverSocket.accept();
				SocketManager manager = new SocketManager(socket);
				Object object = manager.readObject();
				
				processReceivedObject(object);
			}
			catch(NoMoreServerException e) {
				shouldStop = true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				if (socket != null)
					try { socket.close(); }
					catch (Exception e) { e.printStackTrace(); }
			}
		}
	}
	
	protected void processReceivedObject(Object object) throws Exception {
		
		if (object instanceof Connection) {
			processConnection((Connection) object);
		}
		
		else if (object instanceof Order) {
			processOrder((Order) object);
		}
	}

}
